package no.views;

import java.util.ArrayList;

import no.listeners.ScaleListener;
import no.logic.Collision;
import no.testspill.*;
import android.content.Context;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGestureListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.Button;

public class BarrierView extends View implements android.view.GestureDetector.OnGestureListener{
	
	private GestureDetector detector;
	private Canvas canvas;
	public boolean pressed;
	private MotionEvent down;
	private MotionEvent up;
	private boolean first = true;
	private Bitmap background;
	private Bitmap scaledBackground;
	private ArrayList<float[]> lineCoords;
	private ArrayList<LineSegment> lineSegs;
	private Ball2 ball;
	private float height;
	private float width;
	private float doubleTap = 0;
	public long prevMS = System.currentTimeMillis(); //Time of last draw
	public long currentMS = 0; //Current time difference from last draw
	public long second = 0; //Times one second, used for calculating frames per second.
	public int oldFPS = 0; // The one that is painted
	public int currentFPS = 0; //We calculate this untill a second has passed, then set value to old. paint old value for One whole second.
	public long dt = 0;
	
	private ScaleGestureDetector mScaleDetector;
	private float mScaleFactor = 1.f;
	
	boolean newLine = false;
	

	public BarrierView(Context context) {
		super(context);
		detector = new GestureDetector(this);
//		mScaleDetector = new ScaleGestureDetector(context, new ScaleListenerer());
		background = BitmapFactory.decodeResource(getResources(), R.drawable.testmap);
		lineCoords = new ArrayList<float[]>();
		lineSegs = new ArrayList<LineSegment>();
		
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void onDraw(Canvas c) {
		this.canvas = c; 
		super.onDraw(this.canvas);
		
		if(first){
			ball = new Ball2(getContext(), canvas.getHeight(), canvas.getWidth());
			scaledBackground = getResizedBitmap(background, canvas.getHeight(), canvas.getWidth());
			first = false;
		}
//		canvas.scale(mScaleFactor, mScaleFactor);
		
		 
//		Rect src = new Rect(0, 0, background.getWidth(), background.getHeight());
//		Rect dest = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
		
		canvas.drawBitmap(scaledBackground,0,0,null);
//		canvas.drawBitmap(background, src, dest, null);

		if(!lineCoords.isEmpty())drawLines(c);
		if(up!= null){ 
			drawLine(canvas);
		}
		
		calcFPS();
		drawFPS(oldFPS, 20, 50, c);
		
		ball.update(c,lineSegs, scaledBackground);
		invalidate(); 
	}
	
	public void drawLine(Canvas c){
		Paint paint = new Paint();
		paint.setColor(Color.GREEN);
		paint.setStrokeWidth(8);
		paint.setStyle(Paint.Style.STROKE);
		canvas.drawLine(down.getX(), down.getY(), up.getX(), up.getY(), paint);
		if(!pressed && newLine){
			LineSegment seg = new LineSegment(down.getX(), down.getY(), up.getX(), up.getY());
			lineSegs.add(seg);
			System.out.println("Added LineSegment");
			System.out.println(lineSegs.size());
			System.out.println(seg.getStartX() + "," + seg.getStartY() + " " + seg.getEndX() + "," + seg.getEndY());
//			seg.testSeg();
			float[] temp = {down.getX(), down.getY(), up.getX(), up.getY()};
			newLine = false;
			lineCoords.add(temp);
		}
		drawLines(c);
		
	}
	
	

	private void drawLines(Canvas c) {
		Paint paint = new Paint();
		paint.setColor(Color.GREEN);
		paint.setStrokeWidth(8);
		paint.setStyle(Paint.Style.STROKE);
		for (int i = 0; i < lineCoords.size(); i++) {
			c.drawLine(lineCoords.get(i)[0], lineCoords.get(i)[1], lineCoords.get(i)[2], lineCoords.get(i)[3], paint);
		}
		
	} 

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		doubleTap = System.currentTimeMillis();
		pressed = (event.getAction()==MotionEvent.ACTION_UP)? false:true; 
//		mScaleDetector.onTouchEvent(event);
		detector.onTouchEvent(event);
		return true;
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
		
		return true;
	}
	

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		down = e1;
		up = e2;
		newLine = true;
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		
	}
	

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		
		return true;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		System.out.println("PENDING");
	}
	
	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		if(!lineCoords.isEmpty())lineCoords.remove(lineCoords.size()-1);
		if(!lineSegs.isEmpty())lineSegs.remove(lineSegs.size()-1);
		System.out.println(scaledBackground.getPixel((int)e.getX(), (int)e.getY()));
		System.out.println(e.getX());
		System.out.println(e.getY());
		
		Matrix m = canvas.getMatrix();
		
		invalidate();
		return true;
	}
	
	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// create a matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the bit map
		matrix.postScale(scaleWidth, scaleHeight);
		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
		return resizedBitmap;
	}
	
	
	
	 
	private class ScaleListenerer extends ScaleGestureDetector.SimpleOnScaleGestureListener {
	    @Override
	    public boolean onScale(ScaleGestureDetector detector) {
	        mScaleFactor *= detector.getScaleFactor();

	        // Don't let the object get too small or too large.
	        mScaleFactor = Math.max(1.0f, Math.min(mScaleFactor, 5.0f));

	        invalidate();
	        return true;
	    }
	}
	
//	public boolean DoubeTap(){
//		if(Math.abs(doubleTap - System.currentTimeMillis()) <=2){
//			doubleTap = System.currentTimeMillis();
//			return true;
//		}
//		else{
//			doubleTap = System.currentTimeMillis();
//			return false;
//		}
//	}
	
	private void calcFPS() {
	  // TODO Auto-generated method stub
	  long tempTime = System.currentTimeMillis();
	  currentMS = tempTime - prevMS;
	  prevMS = tempTime;
	  second += currentMS;
	  if(second < 1000)currentFPS++;
	  else{
	   second = 0;
	   oldFPS = currentFPS;
	   currentFPS = 0;
	  }
	  dt+=currentMS;
	 }
	
	public void drawFPS(int fps, int posx, int posy, Canvas c){
		  Paint textPaint = new Paint();
		  textPaint.setColor(Color.YELLOW);
		  textPaint.setStyle(Paint.Style.FILL);
		  textPaint.setTextSize(10);
		  c.drawText("FPS: " + fps + "", posx, posy, textPaint);
		 }
	
	
	
	
}	
	
	



